#ifndef _MYTHREAD_HPP_
#define _MYTHREAD_HPP_
#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <string>
#include <functional>
namespace ThreadClass
{
   /*---thread属性类---*/
   class ThreadData
   {
   public:
      ThreadData(const std::string& name,pthread_mutex_t* lock)
            :_name(name)
            ,_lock(lock)
            {}
      std::string& GetName()
      {
         return _name;
      }
      pthread_mutex_t* GetLock() 
      {
         return _lock;
      }
   private:
      std::string _name;
      pthread_mutex_t* _lock;
   };
   class Thread
   {
      using func_t = std::function<void(ThreadData*)>;

   public:
      void Excute()
      {
         _isrunning = true;
         _func(_td);
         _isrunning = false;
      }
   public:
      Thread(func_t func,ThreadData* td)
          : _func(func),_td(td)
      {}
      ~Thread()
      {}
      /*--检测线程状态--*/
      std::string Status()
      {
         if (_isrunning)
            return "Running...";
         else
            return "Stop";
      }
      std::string &GetName()
      {
         return _td->GetName();
      }
      static void *ThreadRoutine(void *args)
      {
         /*--回调--*/
         Thread *self = static_cast<Thread *>(args);
         self->Excute();
         return nullptr;
      }
      void Start()
      {
         /*--传入this指针，就可以在static的成员函数中调取参数启动普通成员函数！---*/
         int n = ::pthread_create(&_tid, nullptr, ThreadRoutine, this);
         if (n != 0)
            throw "线程启动失败！";
      }
      void Stop()
      {
         if (_isrunning == true)
         {
            ::pthread_cancel(_tid);
            _isrunning = false;
         }
      }
      void Join()
      {
         /*--当线程处于退出状态时才需要等待--*/
         int n = ::pthread_join(_tid, nullptr);
         if (n != 0)
            throw "thread wait false! ";
      }
   private:
      pthread_t _tid;
      bool _isrunning;
      /*---回调方法---*/
      func_t _func;
      ThreadData* _td;//线程属性
   };
}
#endif